package com.cos.openapi.services.impl;

import com.cos.openapi.common.ResponseResult;
import com.cos.openapi.common.ResultTable;
import com.cos.openapi.dao.RoleMapper;
import com.cos.openapi.entity.Role;
import com.cos.openapi.services.RoleServices;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: COS
 * @time: 2021/11/24 14:25
 * @description:
 */
@Service
public class RoleServicesImpl implements RoleServices {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public ResultTable getRolePageWithName(Integer page, Integer limit, String name) {
        PageHelper.startPage(page, limit);
        //发送查询语句
        List<Role> roles = roleMapper.getRoleWithName(name);
        PageInfo pi = new PageInfo(roles);
        return new ResultTable(0, "", (int) pi.getTotal(), pi.getList());
    }

    @Override
    public ResponseResult updateStatus(Integer id, Integer status) {
        if (id > 0) {
            int i = roleMapper.updateByPrimaryKeySelective(new Role(id, status));
            if (i > 0) {
                return ResponseResult.getSuccess("账户状态修改成功");
            }
        }
        return ResponseResult.getFail("账户状态修改失败,请稍后再试,或者不试");
    }

    @Override
    public List<Integer> getRoleMenu(Integer roleId) {
        List<Integer> roles = roleMapper.getRoleMenu(roleId);
        return roles;
    }

    @Override
    public ResponseResult assignMenu(Integer roleId, Integer[] menuIds) {
        //1 先删除中间表中所有的roleId 的数据
        roleMapper.delMenuByRoleId(roleId);
        //2 批量新增menuIds 数据中的数据
        //2.1
//        for (Integer menuId : menuIds) {
//            roleMapper.insert(roleId,menuId);
//        }
        //2.2 mybatis的批量处理
        roleMapper.insertMenus(roleId,menuIds);
        return ResponseResult.getSuccess();
    }

    @Override
    public ResponseResult updateRole(Role r) {
        int i = roleMapper.updateByPrimaryKeySelective(r);
        if (i>0) {
            return ResponseResult.getSuccess();
        }
        return ResponseResult.getFail("修改失败");
    }

    @Override
    public ResponseResult add(Role r) {
        int i = roleMapper.insertSelective(r);
        if (i>0) {
            return ResponseResult.getSuccess();
        }
        return ResponseResult.getFail("新增失败");
    }

    @Override
    public List<Role> getAllRole() {
        return roleMapper.getAllRole();
    }
}
